<template>
  <div class="app-container">
    <div class="filter-container">
      <el-form :inline="true" ref="listQuery" :model="listQuery" class="demo-form-inline">
        <!--
        <el-form-item prop="approveOrderId" label="审批单ID">
          <el-input v-model="listQuery.approveOrderId" placeholder="审批单ID" @keyup.enter="handleFilter" />
        </el-form-item>
        -->
        <el-form-item prop="approveOrderTobeType" label="待办待阅类型">
          <el-radio-group v-model="listQuery.approveOrderTobeType">
            <el-radio-button label="">全部</el-radio-button>
            <el-radio-button v-for="(item, index) in getEnumList('ApproveOrderTobeType')" :key="index" :label="item.key">{{item.value}}</el-radio-button>
          </el-radio-group>
        </el-form-item>
        <el-form-item prop="approveOrderTobeTitle" label="待办待阅标题">
          <el-input v-model="listQuery.approveOrderTobeTitle" placeholder="待办待阅标题" @keyup.enter="handleFilter" />
        </el-form-item>
        <el-form-item prop="approveOrderTobeContent" label="待办待阅内容">
          <el-input v-model="listQuery.approveOrderTobeContent" placeholder="待办待阅内容" @keyup.enter="handleFilter" />
        </el-form-item>
        <el-form-item prop="receiveUserId" label="接收人">
          <User v-model="listQuery.receiveUserId" keyName="id" keyShow="name" placeholder="接收人" title="用户查询" :disabled="useUserStore().organization.organizationType !== '1'" />
        </el-form-item>
        <el-form-item label="查看时间">
          <el-date-picker v-model="listQuery.readTimeRange"
                          value-format="YYYY-MM-DD HH:mm:ss"
                          style="width: 380px"
                          type="datetimerange"
                          range-separator="-"
                          start-placeholder="查看时间开始"
                          end-placeholder="查看时间结束" />
        </el-form-item>
        <el-form-item label="处理时间">
          <el-date-picker v-model="listQuery.processTimeRange"
                          value-format="YYYY-MM-DD HH:mm:ss"
                          style="width: 380px"
                          type="datetimerange"
                          range-separator="-"
                          start-placeholder="处理时间开始"
                          end-placeholder="处理时间结束" />
        </el-form-item>
        <el-form-item prop="state" label="状态">
          <el-radio-group v-model="listQuery.state">
            <el-radio-button label="">全部</el-radio-button>
            <el-radio-button v-for="(item,index) in getEnumList('ApproveOrderTobeState')" :label="item.key" :key="index">{{item.value}}</el-radio-button>
          </el-radio-group>
        </el-form-item>
        <el-form-item>
          <el-button v-waves type="success" icon="Search" @click="handleFilter">
            查询
          </el-button>
          <el-button icon="Refresh" @click="handleResetQuery">
            重置
          </el-button>
          <!--
          <el-button v-show="checkAuthByCode('')" type="primary" icon="Edit" @click="handleAdd">
            新增
          </el-button>
          -->
          <el-button v-show="checkAuthByCode('PD0052')" type="primary" icon="Download" @click="handleExport">
            导出
          </el-button>
        </el-form-item>
      </el-form>
    </div>
    <el-divider class="el-divider--horizontal-margin" />
    <el-table v-loading="listLoading"
              :key="tableKey"
              :data="list"
              :row-style="{height: '0'}"
              :cell-style="{padding: '0'}"
              border
              fit
              highlight-current-row
              tooltip-effect="dark"
              @sort-change="handleSortChange"
              @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="39px" />
      <el-table-column align="center" type="index" label="序号" width="60px" />
      <el-table-column v-if="isDebug" align="center" label="ID" prop="id" width="60px" sortable show-overflow-tooltip />
      <el-table-column align="center" label="审批单ID" prop="approveOrderId" min-width="130px" sortable show-overflow-tooltip>
        <template v-slot="{row}">{{ row.approveOrderId }}</template>
      </el-table-column>
      <el-table-column align="center" label="待办待阅类型" prop="approveOrderTobeType" min-width="155px" sortable show-overflow-tooltip>
        <template v-slot="{row}">
          <EnumTag :enum-list="getEnumList('ApproveOrderTobeType')" :enum-key="row.approveOrderTobeType" />
        </template>
      </el-table-column>
      <el-table-column align="center" label="待办待阅标题" prop="approveOrderTobeTitle" min-width="155px" sortable show-overflow-tooltip>
        <template v-slot="{row}">{{ row.approveOrderTobeTitle }}</template>
      </el-table-column>
      <el-table-column align="center" label="待办待阅内容" prop="approveOrderTobeContent" min-width="180px" sortable show-overflow-tooltip>
        <template v-slot="{row}">{{ row.approveOrderTobeContent }}</template>
      </el-table-column>
      <el-table-column align="center" label="接收人" prop="receiveUserId" min-width="130px" sortable show-overflow-tooltip>
        <template v-slot="{row}"><LabelTag :foreignList="userList" :foreignIds="row.receiveUserId" :foreignLabel="'name'" /></template>
      </el-table-column>
      <el-table-column align="center" label="查看时间" prop="readTime" min-width="105px" sortable>
        <template v-slot="{row}">{{ row.readTime }}</template>
      </el-table-column>
      <el-table-column align="center" label="处理时间" prop="processTime" min-width="105px" sortable>
        <template v-slot="{row}">{{ row.processTime }}</template>
      </el-table-column>
      <el-table-column align="center" label="状态" prop="state" min-width="120px" sortable show-overflow-tooltip>
        <template v-slot="{row}">
          <EnumTag :enum-list="getEnumList('ApproveOrderTobeState')" :enum-key="row.state" />
        </template>
      </el-table-column>
      <el-table-column align="center" label="创建时间" width="180px" prop="createTime" sortable show-overflow-tooltip>
        <template v-slot="{row}"><DateTag :timestamp="row.createTime" /></template>
      </el-table-column>
      <el-table-column align="center" label="最后修改时间" width="180px" prop="updateTime" sortable show-overflow-tooltip>
        <template v-slot="{row}"><DateTag :timestamp="row.updateTime" /></template>
      </el-table-column>
      <el-table-column align="center" label="操作" width="160px" fixed="right">
        <template v-slot="{row}">
          <el-button type="primary" link @click="handleView(row)">查看</el-button>
          <!--
          <el-button v-show="checkAuthByCode('')" type="primary" link @click="handleEdit(row)">编辑</el-button>
          -->
          <el-popconfirm confirm-button-text="确定"
                         cancel-button-text="取消"
                         :icon="WarningFilled"
                         icon-color="#626AEF"
                         title="您确定删除么？"
                         @confirm="handleDelete(row)"
                         v-if="checkAuthByCode('PD0051')">
            <template #reference>
              <el-button type="danger" link>删除</el-button>
            </template>
          </el-popconfirm>
          <el-button v-show="checkAuthByCode('')" type="success" link @click="handleViewBusiness(row)">查看单据</el-button>
          <el-button v-show="checkAuthByCode('')"
                     type="success"
                     link
                     @click="handleApproveBusiness(row)"
                     v-if="row.approveOrderTobeType === '1' && row.state === '1' && row.receiveUserId === getUserId()">审核</el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination v-model:total="total" v-model:page="listQuery.pageNum" v-model:limit="listQuery.pageSize" @pagination="getList" />
    <el-dialog v-model="dialogVisible" :title="dialogTypeTitle" width="70%" top="2vh">
      <el-form class="my-form" ref="obj" :model="obj" :rules="rules" label-position="right" :disabled="dialogType === 'view'" label-width="auto">
        <el-form-item v-show="isDebug" label="ID">
          <text>{{ obj.id }}</text>
        </el-form-item>
        <el-form-item label="审批单ID" prop="approveOrderId">
          <el-input v-model="obj.approveOrderId" type="number" placeholder="请输入审批单ID" />
        </el-form-item>
        <el-form-item label="待办待阅类型" prop="approveOrderTobeType">
          <el-radio-group v-model="obj.approveOrderTobeType">
            <el-radio-button v-for="(item, index) in getEnumList('ApproveOrderTobeType')" :label="item.key" :key="index">{{item.value}}</el-radio-button>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="待办待阅标题" prop="approveOrderTobeTitle">
          <el-input v-model="obj.approveOrderTobeTitle" placeholder="请输入待办待阅标题，最多输入100个字符" />
        </el-form-item>
        <el-form-item label="待办待阅内容" prop="approveOrderTobeContent">
          <el-input v-model="obj.approveOrderTobeContent" placeholder="请输入待办待阅内容，最多输入200个字符" />
        </el-form-item>
        <el-form-item label="接收人" prop="receiveUserId">
          <User v-model="obj.receiveUserId" keyName="id" keyShow="name" placeholder="接收人" title="用户查询" />
        </el-form-item>
        <el-form-item label="查看时间" prop="readTime">
          <el-date-picker v-model="obj.readTime" placeholder="请输入查看时间" type="datetime" value-format="YYYY-MM-DD HH:mm:ss" />
        </el-form-item>
        <el-form-item label="处理时间" prop="processTime">
          <el-date-picker v-model="obj.processTime" placeholder="请输入处理时间" type="datetime" value-format="YYYY-MM-DD HH:mm:ss" />
        </el-form-item>
        <el-form-item label="状态" prop="state">
          <el-radio-group v-model="obj.state">
            <el-radio-button v-for="(item,index) in getEnumList('ApproveOrderTobeState')" :label="item.key" :key="index">{{item.value}}</el-radio-button>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="创建时间">
          <text>{{ obj.createTime ? obj.createTime : '自动生成' }}</text>
        </el-form-item>
        <el-form-item label="最后修改时间">
          <text>{{ obj.updateTime ? obj.updateTime : '自动生成' }}</text>
        </el-form-item>
        <el-form-item v-show="isDebug" label="数据版本">
          <text>{{ obj.version }}</text>
        </el-form-item>
      </el-form>
      <div style="text-align:right;">
        <el-button type="info" icon="Close" @click="dialogVisible=false">关闭</el-button>
        <el-button type="primary" icon="Check" v-show="dialogType !== 'view'" @click="doConfirm('obj')">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import baseConfig from '@/mixins/baseConfig'
import {doGet, doPost, doPut, doDelete, doGetDownload} from '@/config/http'
import {alertErrorMsg, customValidator, getEnv, getListPageSize, notifySuccess, svc} from "@/config/common";
import {getUserId} from "@/config/cookie";
import User from "@/views/components/base/selectUser.vue";
import {approveOrderBusinessTypes} from "@/config/common";
import useUserStore from "@/store/modules/user";
import initListStore from '@/store/modules/initList'

const emptyObj = {
  approveOrderId: null, // 审批单ID
  approveOrderTobeType: null, // 待办待阅类型
  approveOrderTobeTitle: null, // 待办待阅标题
  approveOrderTobeContent: null, // 待办待阅内容
  receiveUserId: null, // 接收人ID
  readTime: null, // 查看时间
  processTime: null, // 处理时间
  state: null, // 状态
  id: null,
  createBy: null,
  createTime: null,
  updateBy: null,
  updateTime: null,
  deleted: null,
  version: null,
}

export default {
  name: 'approveOrderTobe_nocache',
  components: {User},
  mixins: [baseConfig],
  data() {
    return {
      svc: 'icims-api',
      obj: Object.assign({}, emptyObj),
      routes: [],
      dialogVisible: false,
      dialogType: 'add',
      dialogTypeTitle: '新增',
      checkStrictly: false,
      defaultProps: {
        children: 'children',
        label: 'title'
      },
      tableKey: 0,
      list: null,
      total: 0,
      listLoading: false,
      listQuery: {
        pageNum: 1,
        pageSize: 10,
        sortField: 'id',
        sortType: 'desc',
        approveOrderId: null,
        approveOrderTobeType: null,
        approveOrderTobeTitle: null,
        approveOrderTobeContent: null,
        receiveUserId: useUserStore().organization.organizationType !== '1' ? getUserId() : '',
        readTimeStart: null,
        readTimeEnd: null,
        readTimeRange: [], //
        processTimeStart: null,
        processTimeEnd: null,
        processTimeRange: [], //
        state: null,
        createTimeStart: null,
        createTimeEnd: null,
        updateTimeStart: null,
        updateTimeEnd: null,
      },
      selectionList: [],
      dialogFormVisible: false,
      dialogStatus: '',
      rules: {
        approveOrderId: [{ required: true, validator: customValidator, min: 1, max: 20, label: '审批单ID', trigger: ['blur', 'change'] }],
        approveOrderTobeType: [{ required: true, validator: customValidator, min: 1, max: 20, label: '待办待阅类型', trigger: ['blur', 'change'] }],
        approveOrderTobeTitle: [{ required: true, validator: customValidator, min: 1, max: 100, label: '待办待阅标题', trigger: ['blur', 'change'] }],
        approveOrderTobeContent: [{ required: false, validator: customValidator, min: 0, max: 200, label: '待办待阅内容', trigger: ['blur', 'change'] }],
        receiveUserId: [{ required: false, validator: customValidator, min: 0, max: 20, label: '接收人ID', trigger: ['blur', 'change'] }],
        readTime: [{ required: false, validator: customValidator, min: 0, max: 0, label: '查看时间', trigger: ['blur', 'change'] }],
        processTime: [{ required: false, validator: customValidator, min: 0, max: 0, label: '处理时间', trigger: ['blur', 'change'] }],
        state: [{ required: false, validator: customValidator, min: 0, max: 20, label: '状态', trigger: ['blur', 'change'] }],
      },
      userList: initListStore().userList,
    }
  },
  computed: {
    routesData() {
      return this.routes
    },
  },
  created() {
    this.getList()
    // this.initList()
  },
  methods: {
    useUserStore,
    getListPageSize,
    approveOrderBusinessTypes,
    getUserId,
    // async initList() {
    //   let p1 = doGet(this.svc, '/user/page', {pageSize: getListPageSize()}, false)
    //   let resArray = await Promise.all([p1])
    //   this.userList = resArray[0]['records']
    // },
    getList() {
      this.listLoading = true
      if (this.listQuery.approveOrderTobeType === null) {
        this.listQuery.approveOrderTobeType = this.$route.query.approveOrderTobeType
      }
      if (this.listQuery.state === null) {
        this.listQuery.state = this.$route.query.state
      }
      this.listQuery.readTimeStart = ''
      this.listQuery.readTimeEnd = ''
      if (this.listQuery.readTimeRange) {
        this.listQuery.readTimeStart = this.listQuery.readTimeRange[0]
        this.listQuery.readTimeEnd = this.listQuery.readTimeRange[1]
      }
      this.listQuery.processTimeStart = ''
      this.listQuery.processTimeEnd = ''
      if (this.listQuery.processTimeRange) {
        this.listQuery.processTimeStart = this.listQuery.processTimeRange[0]
        this.listQuery.processTimeEnd = this.listQuery.processTimeRange[1]
      }
      doGet(this.svc, '/approve-order-tobe/page', this.listQuery).then(res => {
        this.listLoading = false
        this.list = res['records']
        this.total = parseInt(res['total'])
      }).catch(e => {
        console.error(e)
        this.listLoading = false
      })
    },
    handleResetQuery() {
      this.resetForm("listQuery")
      this.listQuery.readTimeStart = ''
      this.listQuery.readTimeEnd = ''
      this.listQuery.readTimeRange = []
      this.listQuery.processTimeStart = ''
      this.listQuery.processTimeEnd = ''
      this.listQuery.processTimeRange = []
    },
    handleFilter() {
      this.listQuery.pageNum = 1
      this.getList()
    },
    handleModifyStatus(row, status) {
      this.$message({
        message: '操作Success',
        type: 'success'
      })
      row.status = status
    },
    handleSelectionChange(data) {
      this.selectionList = data
    },
    handleSortChange(data) {
      const { prop, order } = data
      this.listQuery.sortField = prop
      this.listQuery.sortType = order === 'ascending' ? 'asc' : 'desc'
      this.handleFilter()
    },
    handleEdit(row) {
      this.dialogType = 'edit'
      this.dialogTypeTitle = '编辑'
      this.dialogVisible = true
      this.checkStrictly = true
      this.obj = Object.assign({}, row)
    },
    handleView(row) {
      this.dialogType = 'view'
      this.dialogTypeTitle = '详情'
      this.dialogVisible = true
      this.checkStrictly = false
      this.obj = Object.assign({}, row)
    },
    handleAdd() {
      this.dialogType = 'add'
      this.dialogTypeTitle = '新增'
      this.dialogVisible = true
      this.checkStrictly = true
      this.obj = Object.assign({}, emptyObj)
    },
    handleApproveBusiness(row) {
      this.goTargetByName('approveOrderForm', {id: row.approveOrderId})
    },
    handleViewBusiness(row) {
      doPost(svc, `/customApprove/readApproveTobe/${row.id}`, {}, false)
      doGet(svc, `/approve-order/${row.approveOrderId}`, {}, false).then(res => {
        if (res) {
          switch (res['businessType']) {
            case approveOrderBusinessTypes().budgetProjectTwo:
              this.goTargetByName('projectTwoEdit', {id: res['businessId'], oper: 'view'})
              break
            case approveOrderBusinessTypes().budgetOne:
              this.goTargetByName('budgetOneEdit', {id: res['businessId'], oper: 'view'})
              break
            case approveOrderBusinessTypes().budgetTwo:
              this.goTargetByName('budgetTwoEdit', {id: res['businessId'], oper: 'view'})
              break
            case approveOrderBusinessTypes().budgetNew:
              break
            case approveOrderBusinessTypes().budgetAdjust:
              break
            case approveOrderBusinessTypes().expenditureKpi:
              this.goTargetByName('expenditureKpiEdit', {id: res['businessId'], oper: 'view'})
              break
            case approveOrderBusinessTypes().expenditureQuota:
              this.goTargetByName('expenditureQuotaEdit', {id: res['businessId'], oper: 'view'})
              break
            case approveOrderBusinessTypes().expenditureAdjustment:
              this.goTargetByName('expenditureAdjustmentEdit', {id: res['businessId'], oper: 'view'})
              break
            case approveOrderBusinessTypes().expenditureApplication:
              this.goTargetByName('expenditureApplicationEdit', {id: res['businessId'], oper: 'view'})
              break
            case approveOrderBusinessTypes().expenditureReimbursement:
              this.goTargetByName('expenditureReimbursementEdit', {id: res['businessId'], oper: 'view'})
              break
            case approveOrderBusinessTypes().expenditureReimbursementOther:
              this.goTargetByName('expenditureReimbursementOtherEdit', {id: res['businessId'], oper: 'view'})
              break
            case approveOrderBusinessTypes().contractInitial:
              this.goTargetByName('contractInitialEdit', {id: res['businessId'], oper: 'view'})
              break
            case approveOrderBusinessTypes().contractMain:
              this.goTargetByName('contractMainEdit', {id: res['businessId'], oper: 'view'})
              break
            case approveOrderBusinessTypes().contractSupplemental:break
            case approveOrderBusinessTypes().contractChange:break
            case approveOrderBusinessTypes().contractCash:break
            case approveOrderBusinessTypes().contractBorrow:break
            case approveOrderBusinessTypes().contractChecking:break
            case approveOrderBusinessTypes().contractInterrupt:break
            case approveOrderBusinessTypes().contractTerminate:break
          }
        }
      })
    },
    handleExport() {
      doGetDownload(svc, '/approve-order-tobe/export', this.listQuery)
    },
    handleDelete(row) {
      doDelete(svc, '/approve-order-tobe/' + row.id, {}).then(() => {
        notifySuccess('操作成功')
        this.getList()
      })
    },
    async doConfirm(formName) {
      let v = await this.$refs[formName].validate().catch((err)=>{return err})
      if (v !== true) {
        alertErrorMsg('表单验证不通过，请检查数据。')
        return
      }
      if (this.dialogType === 'edit') {
        doPut(svc, '/approve-order-tobe/modify', this.obj).then(() => {
          notifySuccess('修改成功')
          this.getList()
          this.dialogVisible = false
        })
      } else if (this.dialogType === 'add') {
        doPost(svc, '/approve-order-tobe/add', this.obj).then(() => {
          notifySuccess('新增成功')
          this.getList()
          this.dialogVisible = false
        })
      }
    },
  }
}
</script>
